package au.edu.unsw.infs3634.gamifiedlearning.actiivty;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.litepal.LitePal;

import au.edu.unsw.infs3634.gamifiedlearning.MainActivity;
import au.edu.unsw.infs3634.gamifiedlearning.R;
import au.edu.unsw.infs3634.gamifiedlearning.model.UserModel;
import au.edu.unsw.infs3634.gamifiedlearning.utils.SPUtil;

public class RegisterActivity extends AppCompatActivity {
    private EditText edtName;
    private EditText edtPwd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        edtName = findViewById(R.id.edt_name);
        edtPwd = findViewById(R.id.edt_pwd);
        Button btn_register = findViewById(R.id.btn_register);
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = edtName.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(RegisterActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (name.length() > 10) {
                    Toast.makeText(RegisterActivity.this, "用户名不得超过10位", Toast.LENGTH_SHORT).show();
                    return;
                }
                String pwd = edtPwd.getText().toString();
                if (TextUtils.isEmpty(pwd)) {
                    Toast.makeText(RegisterActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (pwd.length() < 6 || pwd.length() > 10) {
                    Toast.makeText(RegisterActivity.this, "密码必须在6-10位之间", Toast.LENGTH_SHORT).show();
                    return;
                }
                register(name, pwd);
            }
        });
    }

    private void register(String name, String pwd) {
        UserModel userModel = LitePal.where("name = ?", name).findFirst(UserModel.class);
        if (userModel != null) {
            Toast.makeText(this, "该用户已注册", Toast.LENGTH_LONG).show();
            return;
        }
        UserModel _userModel = new UserModel(name, pwd);
        _userModel.save();

        Toast.makeText(this, "注册成功，即将跳转首页", Toast.LENGTH_LONG).show();
        SPUtil.saveInt(this,"userId",_userModel.getId());
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
}
